﻿using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.Windsor.Installer;
using ABC.Core.Configuration;
using ABC.Core.Providers;
using ABC.Core.Web.Routes;
using ABC.Web.Providers;


namespace ABC.Web
{
	public class MvcApplication : HttpApplication
	{
		private static IWindsorContainer container;

		protected void Application_Start()
		{
			BootstrapContainer();
			ViewEngines.Engines.Clear();
			ViewEngines.Engines.Add(new RazorViewEngine());
			AreaRegistration.RegisterAllAreas();
			RegisterGlobalFilters(GlobalFilters.Filters);
			RegisterRoutes(RouteTable.Routes);
		}

		protected void Application_End()
		{
			container.Dispose();
		}

		private static void BootstrapContainer()
		{
            container = new WindsorContainer().Install(FromAssembly.Named("ABC.Core"));
			container.Register(Component.For<IApplicationSettingsProvider>().ImplementedBy<ApplicationSettingsProvider>().LifeStyle.Singleton);
			IoC.Initialize(container);
			var controllerFactory = new WindsorControllerFactory(container.Kernel);
			ControllerBuilder.Current.SetControllerFactory(controllerFactory);
		}

		public static void RegisterGlobalFilters(GlobalFilterCollection filters)
		{
			filters.Add(new HandleErrorAttribute());
		}

		public static void RegisterRoutes(RouteCollection routes)
		{
			routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
			routes.IgnoreRoute("{resource}.ashx/{*pathInfo}");
			routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

			RegisterGuestRoutes(routes);

			routes.Add(new LowercaseRoute("{controller}/{action}/{id}",
			                              new RouteValueDictionary(
			                              	new {controller = "Guest", action = "Index", id = UrlParameter.Optional}),
			                              new MvcRouteHandler()));
		}

		private static void RegisterGuestRoutes(RouteCollection routes)
		{
            routes.MapRoute("GuestRegistration", "register", new { controller = "Guest", action = "Register" });
            routes.MapRoute("GuestForgotPassword", "restore", new { controller = "Guest", action = "Remind" });
		}
	}
}